package com.sslpay.merchant.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.sslpay.common.domain.BusinessException;
import com.sslpay.common.domain.CommonErrorCode;
import com.sslpay.merchant.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * 描述：
 *
 * @author ssl
 * @create 2020/04/21 15:19
 */
@org.springframework.stereotype.Service
@Slf4j
@RefreshScope// 实时刷新配置文件内容
public class SmsServiceImpl implements SmsService {
    @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.effectiveTime}")
    private String smsEffectiveTime;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送手机验证码
     *
     * @param phone
     * @return
     */
    @Override
    public String sendMsg(String phone) throws BusinessException {
        String sendUrl = smsUrl.concat("generate?name=sms&effectiveTime=").concat(smsEffectiveTime);
        // 请求体
        Map<String, Object> body = Maps.newHashMap();
        body.put("phone", phone);
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 组装请求信息：body+header
        HttpEntity httpEntity = new HttpEntity(body, headers);

        // response
        ResponseEntity<Map> responseEntity;
        Map<String, Object> responseBodyMap;
        try {
            responseEntity = restTemplate.exchange(sendUrl, HttpMethod.POST, httpEntity, Map.class);
            log.info("请求验证码服务，得到响应:{}", JSON.toJSONString(responseEntity));
            responseBodyMap = responseEntity.getBody();
        } catch (Exception e) {
            log.error("发送验证码失败。", e);
            throw new BusinessException(CommonErrorCode.E_100116, e);
        }
        if (null == responseBodyMap || null == responseBodyMap.get("result")) {
            throw new BusinessException(CommonErrorCode.E_100116);
        }
        Map result = (Map) responseBodyMap.get("result");
        String key = (String) result.get("key");
        log.info("得到发送验证码对应的key:{}", key);
        return key;
    }

    /**
     * 校验验证码
     *
     * @param verifiyKey
     * @param verifiyCode
     */
    @Override
    public void checkVerifiyCode(String verifiyKey, String verifiyCode) throws BusinessException {
        String url = smsUrl.concat("verify?name=sms&verificationCode=").concat(verifiyCode)
                .concat("&verificationKey=").concat(verifiyKey);
        Map responseMap;
        try {
            //请求校验验证码
            ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.POST,
                    HttpEntity.EMPTY, Map.class);
            responseMap = exchange.getBody();
            log.info("校验验证码，响应内容：{}", JSON.toJSONString(responseMap));
        } catch (Exception e) {
            throw new BusinessException(CommonErrorCode.E_100102, e);
        }
        if (responseMap == null || responseMap.get("result") == null || !(Boolean)
                responseMap.get("result")) {
            throw new BusinessException(CommonErrorCode.E_100102);
        }

    }
}
